<script setup>
import { onMounted, ref, watch } from 'vue'
import request from '@/utils/request';
import { ElMessage, ElNotification } from 'element-plus';
import * as echarts from 'echarts';

let tableData = ref([]);
let total = ref(0);
let keyword = ref("");
let ifShow = ref(false);        //个人总评图表展示
let drawer = ref(false);        //右侧 荣耀记录 抽屉
let activities = ref([]);

let student_id = ref('')

let chart1_xdata_proxy = ref([])
let chart1_ydata_gpa_proxy = ref([])
let chart1_ydata_average_score_proxy = ref([])
let proportion = ref(0);


//生命周期函数
onMounted(() => {
    initMyChart1();
    initMyChart2();

    ElNotification({
        title: '提示',
        message: '该页面为分析页，请输入想要查询的个人汇总信息。',
        // duration: 0,        // duration 设置为0，通知栏不会自动关闭
    })
});

watch(student_id, (newValue, oldValue) => {
    initMyChart1();
});
watch(proportion, (newValue, oldValue) => {
    initMyChart2();
})

const queryByKeyWord = async () => {
    let response = await request.get("/table/page?" + "pageNum=" + 1 + "&pageSize=8" + "&input=" + keyword.value);
    // console.log(keyword.value);
    tableData.value = response.records;
    total.value = response.total;
    // console.log(response.records);
    if (response.total === 0) {
        ElMessage('未查询到数据');
        return;
    }
};
const resetTable = () => {
    total.value = 0;
    tableData.value = [];
};
const handleCurrentChange = async (num) => {
    let all_data = await request.get("/table/all");
    if (total.value != all_data.length) {
        //搜索之后进行页码切换。
        let response = await request.get("/table/page?" + "pageNum=" + num + "&pageSize=8" + "&input=" + keyword.value);
        tableData.value = response.records;
    } else {
        //未进行搜索，页码切换。
        let response2 = await request.get("/table/page/" + num + "/" + 8)
        tableData.value = response2.records;
    }
};
let current_name = ref('');
//提供数据
const drawEchart = async (raw) => {
    let id = JSON.parse(JSON.stringify(raw.id));
    let class_name = JSON.parse(JSON.stringify(raw.className));

    current_name.value = JSON.parse(JSON.stringify(raw.name));

    let response_list = await request.get("/overview/" + id);
    let sorted = response_list.sort((a, b) => a.semester - b.semester);
    let gpa = sorted.map(x => x.gpa);
    let semester = sorted.map(x => x.semester);
    let average_score = sorted.map(x => x.averageScore);

    chart1_xdata_proxy.value = semester;
    chart1_ydata_gpa_proxy.value = gpa;
    chart1_ydata_average_score_proxy.value = average_score;
    student_id.value = id;

    let class_numebr = await request.get('/table/' + class_name);
    // console.log(response_list.map(x => x.rank));
    let rank = response_list.map(x => x.rank).slice(-1)[0];
    if (rank == undefined) {
        ElMessage("抱歉，因为某些原因数据缺失。");
    } else {
        ifShow.value = true;
    }
    proportion.value = (1 - rank / class_numebr) * 100;
};

const initMyChart1 = () => {
    let xData = JSON.parse(JSON.stringify(chart1_xdata_proxy.value));
    let yData_gpa = JSON.parse(JSON.stringify(chart1_ydata_gpa_proxy.value));
    let yData_average = JSON.parse(JSON.stringify(chart1_ydata_average_score_proxy.value));

    const myEchartDom1 = echarts.init(document.getElementById('discount'));
    let option = {
        title: {
            text: current_name.value + "成绩总览",
            top: 10,
            left: 10,
        },
        tooltip: {
            trigger: "axis",
            axisPointer: { type: "cross", },
        },
        grid: {
            top: 60,
            right: 70,
            bottom: 30,
            left: 60,
        },
        legend: {
            top: 0,
            left: "center",
            data: ["均分", "绩点"],
        },
        calculable: true,
        xAxis: {
            type: "category",
            data: xData,
            axisLabel: {
                show: true,
                showMinLabel: true,
                showMaxLabel: true,
                formatter: function (value) {
                    return "第" + value + "学期";
                },
            },
        },
        yAxis: [
            {
                type: "value",
                splitLine: { show: false },
                axisLabel: {
                    show: true,
                    showMinLabel: true,
                    showMaxLabel: true,
                    formatter: function (value) { return value; },
                },
            },
            {
                type: "value",
                splitLine: { show: false },
                axisLabel: {
                    show: true,
                    showMinLabel: true,
                    showMaxLabel: true,
                    formatter: function (value) { return value; },
                },
            },
        ],
        series: [
            {
                name: "绩点",
                type: "line",
                smooth: true,
                yAxisIndex: 0,
                data: yData_gpa,
                label: { show: true }
            },
            {
                name: "均分",
                type: "bar",
                smooth: true,
                yAxisIndex: 1,
                data: yData_average,
                label: { show: true }
            },
        ],
    }

    if (student_id.value != '') {
        myEchartDom1.clear();
        option && myEchartDom1.setOption(option, true);
    } else {
        option && myEchartDom1.setOption(option, true);
    }


};
const initMyChart2 = () => {
    // 仪表盘
    const myEchartDom2 = echarts.init(document.getElementById('dashboard'))
    let p = JSON.parse(JSON.stringify(proportion.value))

    let data = {
        title: "超越班级同学占比(综测)",
        value: p,
        color: {
            pieMini: "#ffca1c", //小圆形颜色
            pieMiniMini: "#fff", //小小圆形颜色
            piePlus: "#5DD1FA", //大圆形颜色
            value: "#687284", //底部数值颜色
        }
    };

    myEchartDom2.setOption({
        backgroundColor: "#fff",
        title: {
            show: true,
            text: data.title || "仪表盘",
            left: "15px",
            top: "5",
            textStyle: {
                color: "#414957",
                fontSize: 16,
                fontFamily: '"Microsoft Yahei","微软雅黑"',
            },
        },
        series: [
            {
                name: "仪表盘",
                type: "gauge",
                splitNumber: 10,
                axisLine: {
                    lineStyle: {
                        color: [
                            [data.value / 100, data.color.piePlus],
                            [1, "#f7f9fc"],
                        ],
                        width: 40,
                    },
                },
                axisLabel: {
                    show: false,
                },
                axisTick: {
                    show: false,
                },
                splitLine: {
                    show: false,
                },
                itemStyle: {
                    show: false,
                },
                detail: {
                    formatter: function (value) {
                        if (value != 0) {
                            var num = Math.round(value * 10) / 10;
                            return parseFloat(num).toFixed(2) + "%";
                        } else {
                            return 0;
                        }
                    },
                    offsetCenter: [0, "70%"],
                    textStyle: {
                        fontSize: 24,
                        fontWeight: "700",
                        color: data.color.value || "#83af98",
                    },
                },
                title: {
                    offsetCenter: [0, "100%"],
                },
                data: [
                    {
                        name: "",
                        value: data.value,
                    },
                ],
                pointer: {
                    show: true,
                    length: "75%",
                    width: 20, //指针粗细
                },
            },
            {
                name: "小圆形",
                type: "pie",
                hoverAnimation: false,
                legendHoverLink: false,
                radius: ["6%", "10%"],
                z: 10,
                label: {
                    normal: {
                        show: false,
                        position: "center",
                    },
                    emphasis: {
                        show: false,
                    },
                },
                labelLine: {
                    normal: {
                        show: false,
                    },
                },
                data: [
                    {
                        value: 0,
                        name: "1",
                        itemStyle: {
                            normal: {
                                color: "red",
                            },
                        },
                    },
                    {
                        value: 100,
                        name: "2",
                        itemStyle: {
                            normal: {
                                color: data.color.pieMini || "#fc9d9a",
                            },
                            emphasis: {
                                color: data.color.pieMini || "#fc9d9a",
                            },
                        },
                    },
                ],
            },
            {
                name: "小圆形",
                type: "pie",
                hoverAnimation: false,
                legendHoverLink: false,
                radius: ["0%", "6%"],
                z: 10,
                label: {
                    normal: {
                        show: false,
                        position: "center",
                    },
                    emphasis: {
                        show: false,
                    },
                },
                labelLine: {
                    normal: {
                        show: false,
                    },
                },
                data: [
                    {
                        value: 0,
                        name: "1",
                        itemStyle: {
                            normal: {
                                color: "red",
                            },
                        },
                    },
                    {
                        value: 100,
                        name: "2",
                        itemStyle: {
                            normal: {
                                color: data.color.pieMiniMini || "#fff",
                            },
                            emphasis: {
                                color: data.color.pieMiniMini || "#fff",
                            },
                        },
                    },
                ],
                axisLabel: {
                    show: true,
                    showMinLabel: true,
                    showMaxLabel: true,
                    formatter: function (value) {
                        // console.log(value);
                        return value + "%";
                    },
                },
            },
        ],
    });
}

const drawerShow = async (id) => {
    let response = await request.get("/award/" + id);
    // console.log(response);
    activities.value = response.map(x => x.award);
    // console.log( response.map(x => x.award));
    drawer.value = true;

    if (activities.value.length == 0) {
        ElNotification({
            title: "提醒",
            message: '抱歉，因为某些原因数据缺失。',
            type: 'warning',
        })
    }
};
</script>

<template>
    <div>
        <el-card style="margin: 2% 2%;">
            <div>
                <div>
                    <div style="margin: 1% 0;">
                        <el-input style="width: 400px;" placeholder="请输入关键词（姓名、班级或者学号）" v-model="keyword"
                            @keyup.enter.native="queryByKeyWord()">
                            <template #suffix>
                                <el-icon @click="keyword = ''">
                                    <CloseBold />
                                </el-icon>
                            </template>
                        </el-input>
                        <el-button style="margin-left: 5px;padding: 0 20px;" type="primary" @click="queryByKeyWord()">
                            <el-icon style="vertical-align: middle; ">
                                <Search />
                            </el-icon>
                            搜索
                        </el-button>
                        <el-button style="margin-left: 5px; padding: 0 20px;" type="warning" @click="resetTable()">
                            <el-icon style="vertical-align: middle;">
                                <Refresh />
                            </el-icon>
                            重置
                        </el-button>
                    </div>

                    <el-table :data="tableData" stripe border :header-cell-style="{ 'background': '#EFEFEF' }">
                        <!-- <el-table-column type="selection" width="55" />     -->
                        <el-table-column prop="id" label="学号" sortable></el-table-column>
                        <el-table-column prop="className" label="班级"></el-table-column>
                        <el-table-column prop="name" label="姓名"></el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button type="success" @click="drawEchart(scope.row)">绘制图表
                                    <el-icon>
                                        <Histogram />
                                    </el-icon>
                                </el-button>
                                <el-button type="primary" @click="drawerShow(scope.row.id)"> 荣誉记录
                                    <el-icon>
                                        <Document />
                                    </el-icon>
                                </el-button>
                            </template>
                        </el-table-column>

                        <el-drawer v-model="drawer" title="荣誉记录" :direction="direction" :append-to-body="true">
                            <el-timeline>
                                <el-timeline-item v-for="(activity, index) in activities" :key="index">
                                    <el-card> {{ activity }}</el-card>
                                </el-timeline-item>
                            </el-timeline>
                        </el-drawer>
                        <!-- <el-empty description="NO DATA" /> -->
                        <template #empty>
                            <el-empty description="没有找到相关数据噢。" />
                            <!-- 没有搜索到相关信息 -->
                        </template>
                    </el-table>
                </div>

                <div style="margin: 15px 0;">
                    <el-pagination background layout="total,prev, pager, next, jumper" :total="total"
                        @current-change="handleCurrentChange" />
                </div>
            </div>

            <div v-show="ifShow" style="margin-top: 30px; width: 100%;  display: flex; flex-direction: row;">
                <div id="discount" style="width: 51vw; height:40vh;"></div>
                <div id="dashboard" style="width: 32vw; height: 40vh;"> </div>
            </div>
        </el-card>
    </div>
</template>

<style lang='scss' scoped></style>